<?php

use Biz\model\taobao\TaoBaoUserAuth;
use Biz\tools\TbkUnion;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;

class unionAction extends CallBackActionPlugin
{
    public function main()
    {
        //https://open.taobao.com/doc.htm?docId=102635&docType=1 用户授权介绍

        $queryParams = $this->getRequest()->getQuery();
        Log::info('get request params', $queryParams);

        $hashUid = $this->getRequest()->getQuery('uid', '');//uid
        $scene = $this->getRequest()->getQuery('scene', '');//场景
        $code = $this->getRequest()->getQuery('code', '');//授权code
        $state = $this->getRequest()->getQuery('state', '');//授权可自定义值字段
        $expirtTimeStamp = $this->getRequest()->getQuery('stamp', '');//授权可自定义值字段
        $result = true;
        if (!$this->checkParams($queryParams)) {
            $result = false;
            $uid = $hashUid ? IdParse::unHashUid($hashUid) : '';
            Log::error('检查参数错误', ['query_params' => $queryParams, 'uid' => $uid]);
        }
        switch ($scene) {
            case TbkUnion::OAUTH_SCENE_DESIGNER_COMMERCE_RID:
                if ($result) {
                    $result = $this->createDesignerCommerceRid($code, $hashUid, $queryParams);
                }
                //授权成功之后的承接页
                $this->redirect(TbkUnion::OAUTH_DESIGNER_COMMERCE_REDIRECT_URL);
                break;
            default:
                break;
        }

        $this->setSuccessWithText('success');
    }

    private function checkParams($params)
    {
        $result = true;
        if (!isset($params['scene']) || empty($params['scene']) || !in_array($params['scene'], TbkUnion::OAUTH_SCENE_MAP)) {
            $result = false;
            Log::error('授权场景scene不正确', ['query_params' => $params]);
        }
        switch ($params['scene']) {
            case TbkUnion::OAUTH_SCENE_DESIGNER_COMMERCE_RID:
                if (!isset($params['uid']) || empty($params['uid'])) {
                    $result = false;
                    Log::error('创建设计师带货-渠道关系id需要uid', ['query_params' => $params]);
                }
                if (!isset($params['code']) || empty($params['code'])) {
                    $result = false;
                    Log::error('创建设计师带货-渠道关系id，需要用户授权code', ['query_params' => $params]);
                }
                $time = time();
                $expireTime = $params['stamp'] ? IdParse::unHashUid($params['stamp']) : 0;
                if (!isset($params['stamp']) || empty($params['stamp'])
                    || $time >= $expireTime || $time <= ($expireTime - TbkUnion::OAUTH_SCENE_DESIGNER_COMMERCE_EXPIRE_TIME)) {
                    $result = false;
                    Log::error('创建设计师带货-渠道关系id，链接已过期失效，当前时间为:' . $time . '#链接有效时间为：' . $expireTime, ['query_params' => $params]);
                }
                break;
            default:
                break;
        }
        return $result;
    }

    private function createDesignerCommerceRid($code, $hashUid, $queryParams)
    {
        $result = true;
        $appKey = TbkUnion::getAppKey();
        $uid = $hashUid ? IdParse::unHashUid($hashUid) : '';
        $info = TaoBaoUserAuth::getByWhere(['uid' => $uid, 'app_key' => $appKey, 'relation_state' => TaoBaoUserAuth::STATE_NORMAL], ['id', 'uid', 'app_key', 'relation_id', 'taobao_user_id', 'taobao_user_nick', 'taobao_open_uid', 'access_token', 'expires_in', 'addtime', 'edittime']);
        if ($info && $info['relation_id']) {//当前uid已经绑定relation_id
            Log::error('当前uid已经绑定了渠道关系id', $info);
            return false;
        }
        //获取access_token
        $tokenResult = TbkUnion::createAccessToken($code);
        if ($tokenResult && isset($tokenResult['access_token'])) {
            Log::info('access token result', $tokenResult);
            $sessionKey = $tokenResult['access_token'];
            //生成relation_id
            $scPUblisherIno = TbkUnion::saveTbkScPublisherInfo($sessionKey, $hashUid);
            Log::info('sc publisher info', $scPUblisherIno);
            if ($scPUblisherIno && isset($scPUblisherIno['relation_id']) && $scPUblisherIno['relation_id']) {
                //rid是否已绑定uid
                $existRid = TaoBaoUserAuth::getByWhere(['relation_id' => $scPUblisherIno['relation_id'], 'app_key' => $appKey, 'relation_state' => TaoBaoUserAuth::STATE_NORMAL], ['id', 'uid', 'app_key', 'relation_id', 'taobao_user_id', 'taobao_user_nick', 'taobao_open_uid', 'access_token']);
                if ($existRid) {
                    Log::error('当前渠道关系id已绑定uid', $existRid);
                    return false;
                }

                //保存uid、relation_id
                $authUserData = [
                    'uid' => $uid,
                    'app_key' => $appKey,
                    'relation_id' => $scPUblisherIno['relation_id'],
                    'taobao_user_id' => $tokenResult['taobao_user_id'] ?? '',
                    'taobao_user_nick' => $tokenResult['taobao_user_nick'] ? urldecode($tokenResult['taobao_user_nick']) : '',
                    'taobao_open_uid' => $tokenResult['taobao_open_uid'] ?? '',
                    'access_token' => $sessionKey,
                    'expires_in' => $tokenResult['expires_in'],
                    'access_result' => json_encode($tokenResult)
                ];
                $result = TaoBaoUserAuth::addData($uid, $appKey, $authUserData);
                if (!$result) {
                    Log::error('创建淘宝授权信息的数据失败', TaoBaoUserAuth::log());
                }
            } else {
                $result = false;
                Log::error('绑定渠道关系id失败', ['query_params' => $queryParams, 'uid' => $uid, 'sc_publisher_info' => $scPUblisherIno]);
            }
        } else {
            $result = false;
            Log::error('获取授权token失败', ['query_params' => $queryParams, 'uid' => $uid]);
        }
        return $result;
    }

}